<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
    >
      <el-form-item label="债权人" prop="creditor">
        <el-input
          v-model="queryParams.creditor"
          placeholder="请输入债权人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="债务人" prop="debtor">
        <el-input
          v-model="queryParams.debtor"
          placeholder="请输入债务人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="初审" prop="checked">
        <el-select
              v-model="queryParams.checked"
              placeholder="初审状态"
              clearable
              style="width: 140px"
            >
              <el-option
                v-for="dict in dict.type.bus_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="复审" prop="repeatChecked">
        <el-select
              v-model="queryParams.repeatChecked"
              placeholder="复审状态"
              clearable
              style="width: 140px"
            >
              <el-option
                v-for="dict in dict.type.bus_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
              style="width: 140px"
            >
              <el-option
                v-for="dict in dict.type.sys_common_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:transfer:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:transfer:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:transfer:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:transfer:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="transferList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="债权人名称" align="center" prop="creditor" />
      <el-table-column label="手机号码" align="center" prop="creditorMobile" />
      <el-table-column label="债务人名称" align="center" prop="debtor" />
      <el-table-column label="财产线索" align="center" prop="hasClue" />
      <el-table-column label="转让金额" align="center" prop="transferPrice" />
      <el-table-column label="初审" align="center" prop="checked">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bus_status"
            :value="scope.row.checked"
          />
        </template>
      </el-table-column>
      <el-table-column label="复审" align="center" prop="repeatChecked">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bus_status"
            :value="scope.row.repeatChecked"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_common_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:transfer:edit']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:transfer:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改债权转让对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="债权人名称" prop="creditor">
          <template>
            <span>{{ form.creditor }}</span>
          </template>
        </el-form-item>
        <el-form-item label="债权人证件号码" prop="creditorNumber">
          <template>
            <span>{{ form.creditorNumber }}</span>
          </template>
        </el-form-item>
        <el-form-item label="手机号码" prop="creditorMobile">
          <template>
            <span>{{ form.creditorMobile }}</span>
          </template>
        </el-form-item>
        <el-form-item label="债务人名称" prop="debtor">
          <template>
            <span>{{ form.debtor }}</span>
          </template>
        </el-form-item>
        <el-form-item label="债务人证件号码" prop="debtorIdnumber">
          <template>
            <span>{{ form.debtorIdnumber }}</span>
          </template>
        </el-form-item>
        <el-form-item label="债务人所在地" prop="city">
          <el-cascader
            :disabled="isUpdate"
            v-model="form.city"
            :options="cityOptions"
            :props="{ label: 'label', value: 'label' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="财产线索" prop="hasClue">
          <el-select
            filterable
            v-model="form.hasClue"
            placeholder="请输入财产线索"
            clearable
            :disabled="isUpdate"
          >
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="债权金额" prop="creditorPrice">
          <template>
            <span>{{ form.creditorPrice }}</span>
          </template>
        </el-form-item>
        <el-form-item label="转让金额" prop="transferPrice">
          <template>
            <span>{{ form.transferPrice }}</span>
          </template>
        </el-form-item>
        <el-form-item label="佣金比例" prop="brokerage">
          <template>
            <span>{{ form.brokerage }}%</span>
          </template>
        </el-form-item>
        <el-form-item label="负责律师" prop="incharge">
          <el-select
            filterable
            v-model="form.incharge"
            placeholder="跟进律师"
            clearable
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="初审" prop="checked">
          <el-radio-group v-model="form.checked">
            <el-radio
              v-for="dict in dict.type.bus_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="复审" prop="repeatChecked">
          <el-radio-group v-model="form.repeatChecked">
            <el-radio
              v-for="dict in dict.type.bus_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="驳回原因"
          prop="reason"
          v-if="form.repeatChecked == 3"
        >
          <el-input
            type="textarea"
            v-model="form.reason"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_common_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="凭证资料" prop="imgs">
          <el-link
            v-for="(file, index) in imgsList"
            :key="index"
            type="primary"
            :underline="false"
            @click="downloadFile(file.url)"
            ><el-image
              v-if="checkFileType(file.url)"
              style="width: 50px; height: 50px"
              :src="file.url"
              fit="contain"
            ></el-image>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              src="https://fast.dgsiy.com/wechat/images/pdficon.png"
              fit="contain"
            ></el-image>
          </el-link>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="loadAgreement(16)">查看协议</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="协议内容"
      :visible.sync="agreementOpen"
      width="800px"
      :append-to-body="true"
      :modal-append-to-body="true"
    >
      <div v-html="agreementContent"></div>
      <div class="sign">
        <div class="signimg">
          <div>甲方：</div>
          <el-image
            style="width: 300px; height: 200px"
            :src="signimg"
            fit="contain"
          ></el-image>
        </div>
        <div class="signimg">
          <div>乙方：</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTransfer,
  getTransfer,
  delTransfer,
  addTransfer,
  updateTransfer,
} from "@/api/business/transfer";
import { listUser } from "@/api/system/user";
import { getNews } from "@/api/business/news";
import citys from "@/utils/city.js";
export default {
  name: "Transfer",
  dicts: ["bus_status", "bus_progress", "sys_yes_no", "sys_common_status"],
  data() {
    return {
      agreementOpen: false,
      agreementContent: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 债权转让表格数据
      transferList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'updateTime desc,createTime desc',
        isAsc: "",
        transferCode: null,
        creditor: null,
        creditorNumber: null,
        creditorMobile: null,
        debtor: null,
        debtorIdnumber: null,
        city: null,
        hasClue: null,
        transferPrice: null,
        incharge: null,
        checked: null,
        repeatChecked: null,
        status: null,
      },
      signimg: "",
      isUpdate: true,
      cityOptions: [],
      // 表单参数
      form: {},
      userList: [],
      imgsList: [],
      // 表单校验
      rules: {
        creditor: [
          { required: true, message: "债权人名称不能为空", trigger: "blur" },
        ],
        transferPrice: [
          { required: true, message: "转让价格不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.cityOptions = citys;
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询债权转让列表 */
    getList() {
      this.loading = true;
      listTransfer(this.queryParams).then((response) => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      listUser({ userModel: 3 }).then((response) => {
        this.userList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    downloadFile(url) {
      const fileUrl = url; // 文件的URL地址
      window.open(fileUrl);
    },
    /** 查看协议内容 */
    loadAgreement(newsId) {
      this.agreementOpen = true;
      getNews(newsId).then((response) => {
        this.agreementContent = response.data.newsContent
      });
    },
    // 表单重置
    reset() {
      this.form = {
        transferId: null,
        transferCode: null,
        creditor: null,
        creditorNumber: null,
        creditorMobile: null,
        debtor: null,
        debtorIdnumber: null,
        city: null,
        hasClue: null,
        transferPrice: null,
        incharge: null,
        checked: null,
        repeatChecked: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    downloadFile(url) {
      const fileUrl = url; // 文件的URL地址
      window.open(fileUrl);
    },
    // 检查文件类型
    checkFileType(file) {
      // 创建一个正则表达式对象，用于匹配常见的图片、视频等文件格式
      const regex = /^.*\.(jpg|jpeg|png|gif)$/i;

      if (regex.test(file)) {
        return true; // 如果符合条件返回true
      } else {
        return false; // 否则返回false
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.transferId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加债权转让";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transferId = row.transferId || this.ids;
      getTransfer(transferId).then((response) => {
        const data = response.data;
        this.form = data;
        this.signimg = process.env.VUE_APP_BASE_API + data.signimg;
        this.form.city = response.data.city.split("-");
        if (data.imgs) {
          const fileArr = data.imgs.split(",");
          fileArr.forEach((item, index) => {
            const arr = item.split(":");
            this.imgsList.push({
              name: arr[0].split("/")[arr[0].split("/").length - 1],
              url: process.env.VUE_APP_BASE_API + arr[0],
            });
          });
        }
        this.open = true;
        this.title = "修改债权转让";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.city =
        this.form.city[0] + "-" + this.form.city[1] + "-" + this.form.city[2];
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.transferId != null) {
            updateTransfer(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransfer(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transferIds = row.transferId || this.ids;
      this.$modal
        .confirm('是否确认删除债权转让编号为"' + transferIds + '"的数据项？')
        .then(function () {
          return delTransfer(transferIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/transfer/export",
        {
          ...this.queryParams,
        },
        `transfer_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scope>
.el-image__inner {
  padding-right: 10px;
}
.sign {
  display: table;
  .signimg {
    width: 50%;
    padding: 20px;
    display: table-cell;
  }
}
</style>